package com.ce.pms.common.web;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletResponse;

import org.jdom.Attribute;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.output.XMLOutputter;

import com.ce.pms.base.web.PmsBaseAction;
import com.ce.pms.common.service.IOrganizationalStructureService;
import com.ce.pms.common.vo.HmDeptVO;
import com.ce.pms.common.vo.OrganizationalStructureVO;
import com.ce.util.BlankUtil;
import com.sitechasia.webx.core.annotation.Out;
import com.sitechasia.webx.core.annotation.Read;
import com.sitechasia.webx.core.support.Page;

public class OrganizationalStructureAction extends PmsBaseAction {

	private IOrganizationalStructureService organizationalStructureService = null;


	/**
	 * 功能描述:  初始化主页面<br>
	 * @return
	 * Create author:许心炜<br>
	 * Create on:2008-10-7  <br>
	 */
	public String initMain(@Read(key="parentFrameId") @Out(key="parentId")String parentFrameId,
							@Read(key="methodName") @Out(key="methodName")String methodName){
		return "main";
	}

	public String initList(){
		setAttribute("totalRows", Integer.valueOf(0));
		return "list";
	}

	/**
	 * 功能描述:  查询员工信息列表
	 * @param organizationalStructureVO
	 * @return
	 * Create author:许心炜
	 * Create on:2008-10-7
	 */
	public String userList(@Read OrganizationalStructureVO organizationalStructureVO,
						 @Read(key="ec_p", defaultValue="1") int pageNo,
			             @Read(key="ec_crd",defaultValue="15")int pageSize){

		organizationalStructureVO.setPageNo(pageNo);
		organizationalStructureVO.setPageSize(pageSize);

		Page page = organizationalStructureService.queryOutUserInfo(organizationalStructureVO);

		setAttribute("employyList", page.getResult());
		setAttribute("totalRows", Integer.valueOf(String.valueOf(page.getTotalCount())));

		return "employyList";
	}

	public IOrganizationalStructureService getOrganizationalStructureService() {
		return organizationalStructureService;
	}
	public void setOrganizationalStructureService(
			IOrganizationalStructureService organizationalStructureService) {
		this.organizationalStructureService = organizationalStructureService;
	}

	//////////////////////////////////////////////////////////////////////////

	/**
	 * 功能描述:获得选择人中的部门和员工的树形<br>
	 * @param <br>
	 * @return<br>
	 *
	 * Create author:xuhaidui<br>
	 * Create on:2008-12-30<br>
	 * Edit author:<br>
	 * Edit on:<br>
	 * Why:<br>
	 */
	public void getAllPersonTree(){
		try {
			   HttpServletResponse response = getResponse();
				response.setContentType("text/xml;charset=UTF-8");
				Element rootElement = new Element("tree");

				Document doc = new Document(rootElement);
				Attribute rootAttri = new Attribute("id", "0");
				rootElement.setAttribute(rootAttri);
				rootElement.setAttribute("select", "true");
				rootElement.setAttribute("tooltip", "根接点");


				List<OrganizationalStructureVO> listVO=organizationalStructureService.getAllPerson();
				if (!BlankUtil.isBlank(listVO)) {
					Map mapdept=new HashMap();

					for(OrganizationalStructureVO vo:listVO){

							Map mapPerson=new HashMap();
							if(!BlankUtil.isBlank(mapdept.get(vo.getDeptId().toString()))){
								mapPerson=(Map)mapdept.get(vo.getDeptId().toString());
							}
							mapPerson.put(vo.getUserId().toString(), vo);
							mapdept.put(vo.getDeptId().toString(), mapPerson);

					}
					for(Iterator  i    =  mapdept.values().iterator();i.hasNext();) {
						Map mapPerson  =  (Map) i.next();
						int count=0;
						Element item = new Element("item");
						for(Iterator  ii    =  mapPerson.values().iterator();ii.hasNext();) {
							OrganizationalStructureVO personvo  =  (OrganizationalStructureVO) ii.next();
							if(count==0){
							item.setAttribute("text", personvo.getDept());
							item.setAttribute("id", personvo.getDeptId().toString());
							item.setAttribute("im1", "root.gif");
							item.setAttribute("im2", "root.gif");
							rootElement.addContent(item);
							count++;
							}

							Element itemperson = new Element("item");
							itemperson.setAttribute("text", personvo.getEmployeeName());
							itemperson.setAttribute("id", personvo.getDeptId().toString()+"_"+personvo.getUserId().toString());
							itemperson.setAttribute("im1", "root.gif");
							itemperson.setAttribute("im2", "root.gif");
							item.addContent(itemperson);
						}
					}

				}

				XMLOutputter XMLOut = new XMLOutputter();
				PrintWriter out = response.getWriter();
				XMLOut.output(doc, out);
				out.flush();

			   } catch(IOException ioe) {

			   }

	}

	/**
	 * 功能描述:初始化选择人的主页面<br>
	 * @param <br>
	 * @return<br>
	 *
	 * Create author:xuhaidui<br>
	 * Create on:2008-12-30<br>
	 * Edit author:<br>
	 * Edit on:<br>
	 * Why:<br>
	 */
	public String initSelectPsrsonMain(@Read(key="frameName") @Out(key="frameName")String frameName,
			@Read(key="callBack") @Out(key="callBack")String callBack,
			@Read(key="multiple",defaultValue="true") @Out(key="multiple")String multiple,
			@Read(key="hadSelectUserId",defaultValue="" ) String hadSelectUserId){
		  this.getRequest().getSession().setAttribute(SELECT_PERSON, null);
		  if(!BlankUtil.isBlank(hadSelectUserId)){
			  if((1+hadSelectUserId.lastIndexOf(","))==hadSelectUserId.length()){
				  hadSelectUserId=hadSelectUserId.substring(0,hadSelectUserId.length()-1);
			  }
			  Map map=new HashMap();
			  String hasSelectArray[]=hadSelectUserId.split(",");
			  for(int i=0;i<hasSelectArray.length;i++){
				  OrganizationalStructureVO vo= organizationalStructureService.queryUserByUserId(Long.valueOf(hasSelectArray[i]));
				  if(!BlankUtil.isBlank(vo)){
					  vo.setUserCode(vo.getDeptId().toString()+"_"+vo.getUserId().toString());
				     map.put(vo.getUserCode(), vo);
				  }
			  }
			  this.getRequest().getSession().setAttribute(SELECT_PERSON, map);
		  }
		return "selectPsrsonMain";
	}

	public static void main(String[] args) {
		String a="1";
		System.out.println(""+(1+a.lastIndexOf(",")));
		System.out.println(""+a.length());
		System.out.println(a.substring(0, a.length()-1));
	}

	/**
	 * 功能描述:已经被选择的员工<br>
	 * @param <br>
	 * @return<br>
	 *
	 * Create author:xuhaidui<br>
	 * Create on:2008-12-30<br>
	 * Edit author:<br>
	 * Edit on:<br>
	 * Why:<br>
	 */
	public String hadSelectPersonList(){
       Map map=(Map)this.getRequest().getSession().getAttribute(SELECT_PERSON);
       if(BlankUtil.isBlank(map)){
    	   map=new HashMap();
       }
	//	List<OrganizationalStructureVO> list = (List)this.getRequest().getSession().getAttribute(SELECT_PERSON);
		this.getRequest().setAttribute("personList", map);
		this.getRequest().setAttribute("totalRows", new Integer(map.size()<18?18:map.size()));
		this.getRequest().setAttribute("totalRecord", new Integer(map.size()));
		return "selectPersonList";
	}

	/**
	 * 功能描述:添加一个员工<br>
	 * @param <br>
	 * @return<br>
	 *
	 * Create author:xuhaidui<br>
	 * Create on:2008-12-30<br>
	 * Edit author:<br>
	 * Edit on:<br>
	 * Why:<br>
	 */
	public String addPerson(@Read OrganizationalStructureVO vo,
			@Read(key="multiple",defaultValue="true")String multiple){
		Map map=(Map)this.getRequest().getSession().getAttribute(SELECT_PERSON);
	       if(BlankUtil.isBlank(map)){
	    	   map=new HashMap();
	       }
	       if("false".equalsIgnoreCase(multiple) && map.size()>0){
	    	   map=new HashMap();
	       }

	       map.put(vo.getUserCode().toString(), vo);
	       this.getRequest().getSession().setAttribute(SELECT_PERSON, map);

	    return hadSelectPersonList();
	}

	/**
	 * 功能描述:删除已经选择了一个员工<br>
	 * @param <br>
	 * @return<br>
	 *
	 * Create author:xuhaidui<br>
	 * Create on:2008-12-30<br>
	 * Edit author:<br>
	 * Edit on:<br>
	 * Why:<br>
	 */
	public String removePerson(@Read OrganizationalStructureVO vo){
		Map map=(Map)this.getRequest().getSession().getAttribute(SELECT_PERSON);
		 if(BlankUtil.isBlank(map)){
	    	   map=new HashMap();
	     }
		 map.remove(vo.getUserCode().toString());
		 this.getRequest().getSession().setAttribute(SELECT_PERSON, map);
		return hadSelectPersonList();
	}

	/**
	 * 功能描述:保存已经选择的人，并返回给所调用的页面<br>
	 * @param <br>
	 * @return<br>
	 *
	 * Create author:xuhaidui<br>
	 * Create on:2008-12-30<br>
	 * Edit author:<br>
	 * Edit on:<br>
	 * Why:<br>
	 */
	public String saveSelectPerson(@Read(key="frameName") @Out(key="frameName")String frameName,
			@Read(key="callBack") @Out(key="callBack")String callBack){
		StringBuffer script=new StringBuffer();
		Map map=(Map)this.getRequest().getSession().getAttribute(SELECT_PERSON);
		if(!BlankUtil.isBlank(map)){
			for(Iterator  ii    =  map.values().iterator();ii.hasNext();) {
				OrganizationalStructureVO personvo  =  (OrganizationalStructureVO) ii.next();
				String userCode=personvo.getUserCode();
				script.append(userCode.substring(userCode.lastIndexOf("_")+1, userCode.length()));
				script.append(",");
				script.append(personvo.getEmployeeName());
				script.append(",");
				script.append(personvo.getDeptId());
				script.append(",");
				script.append(personvo.getDept());
				script.append(";");
			}
			if(script.indexOf(";")!=-1){
				script.deleteCharAt(script.length()-1);
			}
		}

		this.getRequest().setAttribute("saveSelect", script);
		  this.getRequest().getSession().setAttribute(SELECT_PERSON, null);
		return "onlyRefresh";
	}

	/**
	 * 功能描述:获得所有部门列表<br>
	 * @param <br>
	 * @return<br>
	 *
	 * Create author:xuhaidui<br>
	 * Create on:2008-12-30<br>
	 * Edit author:<br>
	 * Edit on:<br>
	 * Why:<br>
	 */
	public String getAllDeptList(@Read(key="frameName") @Out(key="frameName")String frameName,
			@Read(key="callBack") @Out(key="callBack")String callBack,
			@Read(key="multiple",defaultValue="true") @Out(key="multiple")String multiple,
			@Read(key="hadSelectDeptId",defaultValue="" ) String hadSelectDeptId){
		List<HmDeptVO> deptList=organizationalStructureService.getAllDept();
		if(BlankUtil.isBlank(deptList)){
			deptList=new ArrayList();
		}
		 if(!BlankUtil.isBlank(hadSelectDeptId)){
			 if((1+hadSelectDeptId.lastIndexOf(","))==hadSelectDeptId.length()){
				 hadSelectDeptId=hadSelectDeptId.substring(0,hadSelectDeptId.length()-1);
			  }
			  Map map=new HashMap();
			  String hasSelectArray[]=hadSelectDeptId.split(",");
			  for(int i=0;i<hasSelectArray.length;i++){
				  for(HmDeptVO tempVO:deptList){
					  if(hasSelectArray[i].equals(tempVO.getDeptId().toString())){
						  deptList.remove(tempVO);
						  tempVO.setHadSelect("1");
						  deptList.add(tempVO);
						  break;
					  }
				  }

			  }

		 }
		this.getRequest().setAttribute("deptList", deptList);
		this.getRequest().setAttribute("totalRows", new Integer(deptList.size()<18?18:deptList.size()));

	   return "selectDeptList";
	}

	/**
	 * 功能描述:保存所选择的人，并返回给所调用页面<br>
	 * @param <br>
	 * @return<br>
	 *
	 * Create author:xuhaidui<br>
	 * Create on:2008-12-30<br>
	 * Edit author:<br>
	 * Edit on:<br>
	 * Why:<br>
	 */
	public String saveSelectDept(@Read(key="frameName") @Out(key="frameName")String frameName,
			@Read(key="callBack") @Out(key="callBack")String callBack,
			@Read(key="deptIdStr")String deptIdStr){

		List<HmDeptVO> deptList=organizationalStructureService.getSelectDeptList(deptIdStr);
		StringBuffer script=new StringBuffer();
		  for(HmDeptVO vo : deptList){
			  script.append(vo.getDeptId());
			  script.append(",");
			  script.append(vo.getDeptName());
			  script.append(";");
		  }

		  if(script.indexOf(";")!=-1){
				script.deleteCharAt(script.length()-1);
		   }
		  this.getRequest().setAttribute("saveSelect", script);

		return "onlyRefresh";
    }


	public  static  final String SELECT_PERSON="select_person";





}
